#include <QLineEdit>
#include <QPlainTextEdit>
#include "getdomainips.h"

GetDomainIps::GetDomainIps(QWidget *parent)
        : QDialog(parent)
{
    setWindowTitle("查询域名和IP地址--测试程序");
    resize(580, 390);

    lineEdit_InputUrl = new QLineEdit(this);
    lineEdit_InputUrl->setText("www.126.com");

    button_GetDomainIP = new QPushButton("查询域名或IP地址", this);
    button_ClearData = new QPushButton("清除数据信息", this);
    plainTextEdit_DomainIP = new QPlainTextEdit(this);

    QHBoxLayout *topLayout = new QHBoxLayout;
    topLayout->addWidget(lineEdit_InputUrl);
    topLayout->addWidget(button_GetDomainIP);
    topLayout->addWidget(button_ClearData);

    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addLayout(topLayout);
    mainLayout->addWidget(plainTextEdit_DomainIP);

    connect(button_GetDomainIP, &QPushButton::clicked, this, &GetDomainIps::onGetDomainIPClicked);
    connect(button_ClearData, &QPushButton::clicked, this, &GetDomainIps::onClearDataClicked);
}

GetDomainIps::~GetDomainIps() {}

void GetDomainIps::onGetDomainIPClicked()
{
    QString hostname = lineEdit_InputUrl->text().trimmed();
    plainTextEdit_DomainIP->appendPlainText("你所查询主机信息：" + hostname);

    QHostInfo::lookupHost(hostname, this, SLOT(onLookupHostFinished(QHostInfo)));
}

void GetDomainIps::onClearDataClicked()
{
    plainTextEdit_DomainIP->clear();
}

QString GetDomainIps::ProtocolTypeName(QAbstractSocket::NetworkLayerProtocol protocoltype)
{
    switch (protocoltype)
    {
        case QAbstractSocket::IPv4Protocol:
            return "IPv4 Protocol";
        case QAbstractSocket::IPv6Protocol:
            return "IPv6 Protocol";
        case QAbstractSocket::AnyIPProtocol:
            return "Any IP Protocol";
        default:
            return "Unknown Network Layer Protocol";
    }
}

void GetDomainIps::onLookupHostFinished(const QHostInfo &host)
{
    if (host.error() != QHostInfo::NoError) {
        plainTextEdit_DomainIP->appendPlainText("查询失败: " + host.errorString());
        return;
    }

    QList<QHostAddress> addresslist = host.addresses();
    for (const QHostAddress &addr : addresslist)
    {
        plainTextEdit_DomainIP->appendPlainText("协议类型：" + ProtocolTypeName(addr.protocol()));
        plainTextEdit_DomainIP->appendPlainText("IP地址：" + addr.toString());
        plainTextEdit_DomainIP->appendPlainText("");
    }
}
